package com.cmcc.aregister.cs.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Process;
import com.cmcc.aregister.MyApplication;
import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.model.Schedule;
import com.cmcc.sdk.CmccDataStatistics;

public class Utils {
	public static MyLogger logger = MyLogger.getLogger();
	public static MyApplication app = MyApplication.getInstance();

	public static boolean isWifi() {
		ConnectivityManager connectivityManager = (ConnectivityManager) app
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null
				&& activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
			return true;
		}
		return false;
	}

	public static byte[] serialIn(Object obj) {
		if (obj == null) {
			return null;
		}
		ByteArrayOutputStream baos = null;
		ObjectOutputStream oos = null;
		try {
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(obj);
			return baos.toByteArray();
		} catch (Exception e) {
			logger.e(e);
			return null;
		} finally {
			try {
				if (baos != null)
					baos.close();
				if (oos != null)
					oos.close();
			} catch (IOException e) {
				logger.e(e);
			}
		}
	}

	public static Object serialOut(byte[] buf) {
		if (buf == null) {
			return null;
		}
		ByteArrayInputStream baos = null;
		ObjectInputStream ois = null;
		try {
			baos = new ByteArrayInputStream(buf);
			ois = new ObjectInputStream(baos);
			Object o = ois.readObject();
			if (o != null) {
				return o;
			} else {
				return null;
			}
		} catch (Exception e) {
			logger.e(e);
			return null;
		} finally {
			try {
				if (baos != null)
					baos.close();
				if (ois != null)
					ois.close();
			} catch (IOException e) {
				logger.e(e);
			}
		}
	}

	/**
	 * 获取医院等级 B: 三级甲等 C: 三级乙等 D: 三级丙等 E: 二级甲等 F: 二级乙等 G: 二级丙等 H: 一级甲等 I: 一级乙等 J:
	 * 一级丙等 K: 未知
	 */
	public static String getHospitalLevelStr(String string) {
		if ("B".equals(string)) {
			return "三级甲等";
		} else if ("C".equals(string)) {
			return "三级乙等";
		} else if ("D".equals(string)) {
			return "三级丙等";
		} else if ("E".equals(string)) {
			return "二级甲等";
		} else if ("F".equals(string)) {
			return "二级乙等";
		} else if ("G".equals(string)) {
			return "二级丙等";
		} else if ("H".equals(string)) {
			return "一级甲等";
		} else if ("I".equals(string)) {
			return "一级乙等";
		} else if ("J".equals(string)) {
			return "一级丙等";
		} else {
			return "未知";
		}
	}

	/**
	 * 获取科室等级 0 非重点，1省重点,2市重点,3区重点
	 */
	public static String getDepartmentLevelStr(String string) {
		if ("0".equals(string)) {
			return "非重点";
		} else if ("1".equals(string)) {
			return "省重点";
		} else if ("2".equals(string)) {
			return "市重点";
		} else {
			return "区重点";
		}
	}

	/**
	 * 获取出诊班别 am 上午;pm 下午
	 */
	public static String getTimeType(String string) {
		if ("am".equals(string)) {
			return "上午";
		} else {
			return "下午";
		}
	}

	/**
	 * 获取本地订单状态
	 */
	public static String getStatus(String string) {
		if ("-1".equals(string)) {
			return app.getString(R.string.order_status_1);
		} else if ("0".equals(string)) {
			return app.getString(R.string.order_status_0);
		} else if ("1".equals(string)) {
			return app.getString(R.string.order_status_2);
		} else if ("2".equals(string)) {
			return app.getString(R.string.order_status_3);
		} else if ("3".equals(string)) {
			return app.getString(R.string.order_status_4);
		} else if("4".equals(string)){
			return app.getString(R.string.order_status_5);
		}
		else {
			return app.getString(R.string.order_status_6);
		}
	}

	/**
	 * 获取本地订单按钮状态
	 */
	public static String getBtnStatus(String string) {
		if ("1".equals(string) || "2".equals(string)) {
			return app.getString(R.string.cancel_order);
		} else {
			return app.getString(R.string.again_order);
		}
	}

	/**
	 * 获取异地订单状态
	 */
	public static String getOtherStatus(String string) {
		if ("0".equals(string)) {
			return app.getString(R.string.order_other_status_0);
		} else if ("1".equals(string)) {
			return app.getString(R.string.order_other_status_1);
		} else if ("2".equals(string)) {
			return app.getString(R.string.order_other_status_2);
		} else if ("3".equals(string)) {
			return app.getString(R.string.order_other_status_3);
		} else if ("4".equals(string)) {
			return app.getString(R.string.order_other_status_4);
		} else if ("5".equals(string)) {
			return app.getString(R.string.order_other_status_5);
		} else if ("6".equals(string)) {
			return app.getString(R.string.order_other_status_6);
		} else if ("7".equals(string)) {
			return app.getString(R.string.order_other_status_7);
		} else if ("8".equals(string)) {
			return app.getString(R.string.order_other_status_8);
		} else if ("9".equals(string)) {
			return app.getString(R.string.order_other_status_9);
		} else {
			return app.getString(R.string.order_other_status_10);
		}
	}

	/**
	 * 自动预约任务状态
	 */
	public static String getAutoAppointTaskStatus(String string) {
		if ("0".equals(string)) {
			return app.getString(R.string.task_status_0);
		} else if ("1".equals(string)) {
			return app.getString(R.string.task_status_1);
		} else if ("2".equals(string)) {
			return app.getString(R.string.task_status_2);
		} else if ("3".equals(string)) {
			return app.getString(R.string.task_status_3);
		} else if ("4".equals(string)) {
			return app.getString(R.string.task_status_4);
		} else {
			return app.getString(R.string.task_status_5);
		}
	}
	
	/**
	 * 号源提醒任务状态
	 */
	public static String getHaoyuanTipTaskStatus(String string) {
		if ("0".equals(string)) {
			return app.getString(R.string.haoyuan_task_status_0);
		} else if ("1".equals(string)) {
			return app.getString(R.string.haoyuan_task_status_1);
		} else if ("2".equals(string)) {
			return app.getString(R.string.haoyuan_task_status_2);
		} else if ("3".equals(string)) {
			return app.getString(R.string.haoyuan_task_status_3);
		} else {
			return app.getString(R.string.haoyuan_task_status_4);
		} 
	}
	
	/**
	 * 号源提醒类型
	 */
	public static String getHaoyuanTipType(String string) {
		if ("1".equals(string)) {
			return app.getString(R.string.haoyuan_tip_type_1);
		} else{
			return app.getString(R.string.haoyuan_tip_type_2);
		} 
	}
	
	/**
	 * 是否可预约
	 */
	public static String getCanAppoint(String string) {
		if ("0".equals(string)) {
			return app.getString(R.string.can_appoint_0);
		} else{
			return app.getString(R.string.can_appoint_1);
		} 
	}

	/**
	 * 获取异地订单支付状态
	 */
	public static String getOtherPaystatus(String string) {
		if ("0".equals(string)) {
			return app.getString(R.string.order_other_paystatus_0);
		} else if ("1".equals(string)) {
			return app.getString(R.string.order_other_paystatus_1);
		} else if ("2".equals(string)) {
			return app.getString(R.string.order_other_paystatus_2);
		} else if ("3".equals(string)) {
			return app.getString(R.string.order_other_paystatus_3);
		} else if ("4".equals(string)) {
			return app.getString(R.string.order_other_paystatus_4);
		} else if ("5".equals(string)) {
			return app.getString(R.string.order_other_paystatus_5);
		} else if ("6".equals(string)) {
			return app.getString(R.string.order_other_paystatus_6);
		} else {
			return app.getString(R.string.order_other_paystatus_6);
		}
	}

	/**
	 * 获取异地订单类型
	 */
	public static String getReservationType(String string) {
		if ("0".equals(string)) {
			return app.getString(R.string.common_service);
		} else {
			return app.getString(R.string.vip_service);
		}
	}

	public static String getOtherDesc(String desc) {
		if (desc==null) {
			return MyApplication.getInstance().getString(R.string.now_no_data);
		} else {
			return desc;
		}
	}

	/**
	 * 修改请求地址,添加client_auth,token,type三个参数以及map中的参数
	 * 
	 * @param _httpUri
	 * @param map
	 * @return
	 */
	public static String changeUrl(String _httpUri, Map<String, String> map) {
		StringBuffer buf = new StringBuffer();
		buf.append(_httpUri)
				.append("&client_auth=" + GlobalSetting.CLIENT_AUTH)
				.append("&token=" + GlobalSetting.TOKEN);
		if (map != null) {
			for (String key : map.keySet()) {
				buf.append("&" + key + "=" + map.get(key));
			}
		}
		return buf.toString().replaceAll("=null", "=").replaceAll(" ", "")
				.trim();
	}

	public static String changeUrl2(String _httpUri, Map<String, String> map) {
		StringBuffer buf = new StringBuffer(_httpUri);
		if (map != null) {
			for (String key : map.keySet()) {
				buf.append("&" + key + "=" + map.get(key));
			}
		}
		return buf.toString().replaceAll("=null", "=").replaceAll(" ", "")
				.trim();
	}

	public static String getParams(Map<String, String> map) {
		StringBuffer buf = new StringBuffer();
		if (map != null) {
			for (String key : map.keySet()) {
				buf.append("&" + key + "=" + map.get(key));
			}
		}
		return buf.toString().replaceAll("=null", "=").replaceAll(" ", "")
				.trim();
	}

	/**
	 * 异地预约请求地址
	 * 
	 * @param _httpUri
	 * @param map
	 * @return
	 */
	public static String changeUrl_other(String _httpUri,
			Map<String, String> map) {
		StringBuffer buf = new StringBuffer();
		buf.append(_httpUri);
		if (map != null) {
			for (String key : map.keySet()) {
				buf.append("&" + key + "=" + map.get(key));
			}
		}
		return buf.toString().replaceAll("=null", "=").replaceAll(" ", "")
				.trim();
	}

	public static HttpURLConnection getHttpConnection(String urlstr) {
		try {
			URL url = new URL(urlstr);
			HttpURLConnection httpConn = null;
			httpConn = (HttpURLConnection) url.openConnection();
			httpConn.setConnectTimeout(1000 * 30);
			httpConn.setReadTimeout(1000 * 30);
			httpConn.setDoInput(true);
			return httpConn;
		} catch (IOException e) {
		}
		return null;
	}

	public static Bitmap writeNetToFileImage(String uri, File file) {
		logger.d("---writeNetToFileImage---start" + uri);
		InputStream is = null;
		HttpURLConnection c = null;
		BufferedOutputStream bos = null;
		Bitmap bit = null;
		try {
			c = getHttpConnection(uri);
			c.connect();
			is = c.getInputStream();
			BitmapFactory.Options opts = new BitmapFactory.Options();
			// opts.inSampleSize = 1;
			bit = getPicFromBytes(readStream(is), opts);
			// bit = getPicFromBytes(readStream(is), new
			// BitmapFactory.Options());
			bit.compress(CompressFormat.PNG, 100, new FileOutputStream(file));
		} catch (Exception e) {
			logger.e(e);
		} finally {
			if (bos != null)
				try {
					bos.close();
				} catch (IOException e) {
					logger.e(e);
				}
			if (is != null)
				try {
					is.close();
				} catch (IOException e) {
					logger.e(e);
				}
			if (c != null)
				c.disconnect();
		}
		logger.d("---writeNetToFileImage---end");
		return bit;
	}

	/**
	 * @param 将图片内容解析成字节数组
	 * @param inStream
	 * @return byte[]
	 * @throws Exception
	 */
	public static byte[] readStream(InputStream inStream) throws Exception {
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;
	}

	/**
	 * 这个函数会对图片的大小进行判断，并得到合适的缩放比例，比如2即1/2,3即1/3
	 * 
	 * @param options
	 * @param target
	 * @return
	 */
	public static int computeSampleSize(BitmapFactory.Options options,
			int target) {
		int w = options.outWidth;
		int h = options.outHeight;
		int candidateW = w / target;
		int candidateH = h / target;
		int candidate = Math.max(candidateW, candidateH);
		if (candidate == 0)
			return 1;
		if (candidate > 1) {
			if ((w > target) && (w / candidate) < target)
				candidate -= 1;
		}
		if (candidate > 1) {
			if ((h > target) && (h / candidate) < target)
				candidate -= 1;
		}
		return candidate;
	}

	/**
	 * @param 将字节数组转换为ImageView可调用的Bitmap对象
	 * @param bytes
	 * @param opts
	 * @return Bitmap
	 */
	public static Bitmap getPicFromBytes(byte[] bytes,
			BitmapFactory.Options opts) {
		opts.inJustDecodeBounds = true;
		if (bytes != null) {
			BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
			int w = 100;
			opts.inSampleSize = computeSampleSize(opts, w);
			opts.inJustDecodeBounds = false;
			opts.inDither = false;
			opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
			if (opts != null) {
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
						opts);
			} else {
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
			}
		}
		return null;
	}

	public static int computeSampleSize(BitmapFactory.Options options,
			int minSideLength, int maxNumOfPixels) {
		int initialSize = computeInitialSampleSize(options, minSideLength,
				maxNumOfPixels);

		int roundedSize;
		if (initialSize <= 8) {
			roundedSize = 1;
			while (roundedSize < initialSize) {
				roundedSize <<= 1;
			}
		} else {
			roundedSize = (initialSize + 7) / 8 * 8;
		}

		return roundedSize;
	}

	private static int computeInitialSampleSize(BitmapFactory.Options options,
			int minSideLength, int maxNumOfPixels) {
		double w = options.outWidth;
		double h = options.outHeight;

		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
				.sqrt(w * h / maxNumOfPixels));
		int upperBound = (minSideLength == -1) ? 100 : (int) Math.min(
				Math.floor(w / minSideLength), Math.floor(h / minSideLength));

		if (upperBound < lowerBound) {
			// return the larger one when there is no overlapping zone.
			return lowerBound;
		}

		if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
			return 1;
		} else if (minSideLength == -1) {
			return lowerBound;
		} else {
			return upperBound;
		}
	}

	// 使用该算法，就可动态计算出图片的inSampleSize。
	public static Options getOptions(String imageFile) {
		Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(imageFile, opts);
		opts.inSampleSize = computeSampleSize(opts, -1, 100 * 100);
		opts.inJustDecodeBounds = false;
		return opts;
	}

	public static String changePicUrl(String urlstr) {	
		String  name=urlstr.substring(urlstr.lastIndexOf("/")+1);
		return name;
	}

	public static void createMVFolderPrivate() {
		createFolderPrivate(GlobalSetting.CACHE_PIC_PATH);
	}

	private static void createFolderPrivate(String path) {
		File file = new File(path);
		if (!file.exists()) {
			logger.i("---create folder---start");
			file.mkdirs();
		} else {
			if (!file.isDirectory()) {
				logger.i("---delete file---start");
				file.delete();
				logger.i("---create folder---start");
				file.mkdirs();
			}
		}

		if (file.exists() && file.canRead() && file.canWrite()) {
			logger.i("---create folder---success");
		} else {
			logger.i("---create folder---fail");
		}
	}

	/**
	 * 医生按姓名排序
	 */
	public static List<Schedule> sequenceDoctorListByName(List<Schedule> list) {
		Collections.sort(list, new Comparator<Schedule>() {
			@Override
			public int compare(Schedule item1, Schedule item2) {
				int int_1 = item1.doctor.doctor_name.hashCode();
				int int_2 = item2.doctor.doctor_name.hashCode();
				if (int_1 >= int_2) {
					return 1;
				} else {
					return -1;
				}
			}
		});
		return list;
	}

	/**
	 * 医生按出诊日期排序
	 */
	public static List<Schedule> sequenceDoctorListByTime(List<Schedule> list) {
		Collections.sort(list, new Comparator<Schedule>() {
			@Override
			public int compare(Schedule item1, Schedule item2) {

				if (getTime(item1.to_date) >= getTime(item2.to_date)) {
					return 1;
				} else {
					return -1;
				}
			}
		});
		return list;
	}

	@SuppressLint("SimpleDateFormat")
	public static long getTime(String dateString) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date new_data = null;
		try {
			new_data = sdf.parse(dateString);
		} catch (Exception e) {
			e.printStackTrace();
			logger.e(dateString);
			new_data = new Date();
		}
		return new_data.getTime();
	}

	@SuppressLint("NewApi")
	public static void exitProgram() {
		if (!ConfigUtilHelper.getMobile(app).equals("")) {
			CmccDataStatistics
					.Comm_Logout(app, ConfigUtilHelper.getMobile(app));
		}
		// ActivityManager activityManager = (ActivityManager) app
		// .getSystemService(Context.ACTIVITY_SERVICE);
		MyApplication.getInstance().getIDatabase().deleteOutTimeCache();
		/*
		 * if (android.os.Build.VERSION.SDK_INT < 8) {
		 * activityManager.restartPackage(app.getPackageName());
		 * Process.killProcess(Process.myPid()); } else {
		 * activityManager.killBackgroundProcesses(app.getPackageName());
		 * Process.killProcess(Process.myPid()); }
		 */
		MyApplication.getInstance().exit();
	}

	public static boolean isLogin(Context context) {
		return context.getSharedPreferences(
				ConfigUtilHelper.INFO_VISIBLE_PREFS, Context.MODE_PRIVATE)
				.getBoolean(ConfigUtilHelper.IS_LOGIN, false);
	}

	/**
	 * 判断传入的字符串是否为空，其中，str="null"与str="NULL"均视为空值
	 * 
	 * @param str
	 * @return 传入的字符串为空返回true，反之返回flase
	 */
	public static boolean isEmpty(String str) {
		if (str == null || "".equals(str) || str.length() == 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 判断传入的字符串是否不为空
	 * 
	 * @param str
	 * @return 传入的字符串不为空返回true，反之返回false
	 */
	public static boolean isNotEmpty(String str) {
		if (str != null && !"".equalsIgnoreCase(str) && str.length() > 0
				&& !"null".equalsIgnoreCase(str)) {
			return true;
		} else {
			return false;
		}

	}
}
